package com.xiumu.securitydemo.config.security.handler;

import com.xiumu.securitydemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.DigestUtils;

/**
 * @Author xiumu
 * @Date 2020/5/28 11:27
 */
@Slf4j
//@Component
public class AuthenticationProviderImpl implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String userName = (String) authentication.getPrincipal(); // 这个获取表单输入中返回的用户名;
        String password = (String) authentication.getCredentials(); // 这个是表单中输入的密码；
        String encodePwd = DigestUtils.md5DigestAsHex(password.getBytes());

        UserDetails userInfo = userService.loadUserByUsername(userName);
        if (userInfo == null){
            throw new BadCredentialsException("用户名密码不正确，请重新登陆！");
        }
        if (!userInfo.getPassword().equals(encodePwd)) {
            log.info("用户名密码不正确，请重新登陆！");
            throw new BadCredentialsException("用户名密码不正确，请重新登陆！");
        }
        return new UsernamePasswordAuthenticationToken(userName,password,userInfo.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
